<template>
	<view class="goodsdetail">
		<page-head :transparent='true'>
			<slot slot="title">{{title.length>10?title.substr(0,10)+'...':title}}</slot>
			<slot slot="right">{{''}}</slot>
		</page-head>
		<view class="goods-detail-row" v-if="businessCode > -1">
			<view class="goods-detail-img">
				<lazy-image class="lazy-image" :realSrc="picUrl"></lazy-image>
				<!-- <image :src="picUrl" mode="widthFix"></image> -->
			</view>
			<view class="goods-detail-title">{{ skuName }}</view>
			<view class="goods-detail-money">
				<text class="money-text">
					到手价
					<text class="money-price">￥{{ wlPrice_after }}</text>
				</text>
			</view>
			<view style="height: 10px;"></view>

			<view class="goods-detail-coupon" @click="validaUserInfo" v-if="discount != ''">
				<view class="coupen-price">
					<view class="coupen-money">抵 ￥{{ discount }}</view>
					<view class="rang-text" v-if="discount == 0">有效期 无</view>
					<view class="rang-text" v-else>有效期 {{ spread_start_at }}-{{ spread_end_at }}</view>
				</view>
				<view class="coupen-time-rang">点击领取</view>
			</view>

			<view style="height: 10px;"></view>
			<!-- <view class="goods-detail-btn" @click="validaUserInfo"><button>立即兑换</button></view> -->
		</view>

		<!-- 查看详情 -->
		<view class="look-detil" @click="lookDetil" v-if="businessCode > -1">
			查看详情
			<image :class="[detilMsg ? 'rotate' : '']" src="../../static/img/search/down.png" mode="aspectFill"></image>
		</view>

		<view class="products-detail" :class="[detilMsg ? 'products-detail1' : 'products-detail2']">
			<view class="products-detail-img" v-for="(item, index) in detailList" :key="index">
				<image :src="item" mode="aspectFill"></image>
			</view>
		</view>
		<view class="hot-row">
			<text>热门推荐</text>
		</view>
		<jd-goods-list :goodsList="goodsList" :platform="platform" @eventClick="toDetail($event)" :loadingText="'我也是有底线的'"></jd-goods-list>
		<view style="padding-bottom: 160px;"></view>
		<foot-tab :footerList="footerList" @goSeller="toPlatform" @goChange="validaUserInfo"></foot-tab>
		<w-loading text="加载中.." mask="1" click="0" ref="loading"></w-loading>
	</view>
</template>

<script>
	import JdGoodsList from '@/components/jd-goods-list.vue';

	let seller = '',
		urlName = '',
		deduction = '1',
		couponurl = '',
		skuId = '',
		h5Url = '',
		appUrl = '';
	export default {
		onShow() {
			window.genCommonData();
		},
		components: {
			JdGoodsList
		},
		onLoad(event) {
			seller = event.seller;
			this.sellerGo = seller;
			if (seller == '1' || seller == '京东') {
				this.platform = '京东';
				urlName = 'jd';
				deduction = '1';
			} else if (seller == '11' || seller == '拼多多') {
				this.platform = '拼多多';
				urlName = 'pdd';
				deduction = '11';
			} else {
				this.platform = '京东';
				urlName = 'jd';
				deduction = '1';
			}
			skuId = event.skuId;
			let cid = event.cid;
			this.genGoodsDetail(skuId);
			this.genHotGoodsList(cid);
		},
		data() {
			return {
				goodsList: [],
				picUrl: '',
				skuName: '',
				wlPrice_after: '',
				discount: '',
				spread_start_at: '',
				spread_end_at: '',
				footerList: [],
				detailList: [],
				detilMsg: false,
				platform: '',
				title: '',
				businessCode: 0,
			};
		},
		methods: {
			toPlatform(e) {
				appNavigateTo(e.item_url);
			},
			genGoodsDetail(skuId) {
				uni.showLoading({
					title: 'loading...'
				});
				uni.request({
					url: this.$serverUrl + '/coupon-product/' + urlName + '/goods/detail',
					method: 'POST',
					dataType: 'json',
					contentType: 'application/json',
					data: {
						skuid: skuId
					},
					success: res => {
						this.businessCode = res.data.businessCode;
						if (res.data.businessCode == -1) {
							uni.showToast({
								icon: 'none',
								title: '商品已下架'
							});
						} else {
							let datas = res.data.data;
							console.log('goodsName===' + datas.skuName);
							this.title = datas.skuName;
							this.detailList = datas.picUrls;
							this.picUrl = datas.picUrl;
							this.skuName = datas.skuName;
							this.wlPrice_after = datas.wlPrice_after;
							this.discount = parseInt(datas.discount);
							Date.prototype.toLocaleString = function() {
								return this.getFullYear() + '/' + (this.getMonth() + 1) + '/' + this.getDate();
							};
							let startTime = new Date(datas.beginTime * 1000);
							let endTime = new Date(datas.endTime * 1000);
							this.spread_start_at = startTime.toLocaleString();
							this.spread_end_at = endTime.toLocaleString();
							this.footerList = [{
								wlPrice: datas.wlPrice,
								sellerGo: seller == 1 ? '京东' : '拼多多',
								wlPrice_after: datas.wlPrice_after,
								item_url: datas.materiaUrl
							}];
							if (deduction == 1) {
								couponurl = datas.couponurl;
							}
						}

						uni.hideLoading();
					}
				});
			},
			setBackColor() {
				// #ifdef H5
				uni.setNavigationBarColor({
					frontColor: '#ffffff',
					backgroundColor: '#FF0000'
				});
				// #endif

				// #ifdef APP-PLUS
				uni.setNavigationBarColor({
					frontColor: '#ffffff',
					backgroundColor: '#FF0000'
				});
				// #endif

				// #ifdef MP
				uni.setNavigationBarColor({
					frontColor: '#000000',
					background: '#FF0000'
				});
				// #endif
			},
			genHotGoodsList(cid) {
				uni.request({
					url: this.$serverUrl + '/coupon-product/' + urlName + '/goods/list',
					method: 'POST',
					data: {
						cid: cid,
						page: 1,
						pagesize: 20
					},
					success: res => {
						let datas = res.data;
						this.goodsList = datas.data;
					}
				});
			},
			lookDetil() {
				if (this.detilMsg) {
					this.detilMsg = false;
				} else {
					this.detilMsg = true;
				}
			},
			setTitle(title) {
				this.title = title;
				uni.setNavigationBarTitle({
					title: title
				});
			},
			toDetail(e) {
				h5RedirectTo({
					url: '../detail/detail?skuId=' + e.skuId + '&cid=' + e.cid + '&title=' + e.skuName + '&seller=' + seller
				});
			},
			exchange() {
				uni.showModal({
					content: '确认使用余额兑换该优惠券，此操作不可撤销？',
					showCancel: true,
					success: res => {
						if (res.confirm) {
							this.$refs.loading.open();
							if (deduction == '1') {
								this.genJDurl();
							} else if (deduction == '11') {
								this.genPDDurl();
							}
						}
					}
				});
			},
			async exchangeCoupon() {
				try {
					console.log('start de');
					uni.request({
						url: this.$usereq + '/coupon-customer/rechargeable/consume/deduction',
						method: 'POST',
						header: {
							'blade-auth': decodeURI(uni.getStorageSync('token')) || decodeURI(UrlParam().token),
							'content-type': 'application/json'
						},
						data: {
							deduction: deduction, //平台id
							deductionAmount: this.discount,
							picUrl: this.picUrl,
							skuId: skuId,
							skuName: this.skuName,
							wlPrice: this.footerList[0].wlPrice,
							wlPriceAfter: this.wlPrice_after,
							endTime: this.spread_end_at.replace('/', '-').replace('/', '-'),
							startTime: this.spread_start_at.replace('/', '-').replace('/', '-'),
							htmlQuanUrl: encodeURIComponent(h5Url),
							appQuanUrl: encodeURIComponent(appUrl)
						},
						success: res => {
							this.$refs.loading.close();
							let datas = res.data;
							if (datas.code == 200) {
								uni.showToast({
									icon: 'none',
									title: '领取成功'
								});
								this.jardePlatform();
							} else if (datas.code == -200) {
								uni.showModal({
									title: '',
									content: '您已兑换过该优惠券，现在去购买吗？',
									showCancel: true,
									cancelText: '取消',
									confirmText: '确定',
									success: res => {
										if (res.confirm) {
											this.jardePlatform();
										}
									},
									fail: () => {},
									complete: () => {}
								});
							} else if (datas.code == 401) {
								this.valida();
							} else {
								uni.showToast({
									icon: 'none',
									title: datas.msg
								});
							}
						}
					});
				} catch (e) {
					uni.hideLoading();
					console.log(e.message);
				}
			},
			validaUserInfo() {
				try {
					const userInfo = uni.getStorageSync('token');
					if (userInfo != '' && userInfo != null) {
						uni.request({
							url: this.$usereq + '/coupon-customer/rechargeable/consume/validatorDeduction',
							method: 'POST',
							header: {
								'blade-auth': decodeURI(uni.getStorageSync('token')) || decodeURI(UrlParam().token),
								'content-type': 'application/json'
							},
							data: {
								deduction: deduction, //平台id
								deductionAmount: this.discount,
								picUrl: this.picUrl,
								skuId: skuId,
								skuName: this.skuName,
								wlPrice: this.footerList[0].wlPrice,
								wlPriceAfter: this.wlPrice_after,
								endTime: '',
								startTime: '',
								htmlQuanUrl: '',
								appQuanUrl: ''
							},
							success: res => {
								let datas = res.data;
								if (datas.code == 200) {
									uni.showModal({
										title: '',
										content: '您已兑换过该优惠券，现在去购买吗？',
										showCancel: true,
										cancelText: '取消',
										confirmText: '确定',
										success: res => {
											if (res.confirm) {
												let result = datas.data;
												appNavigateTo(result.htmlQuanUrl)
											}
										}
									});
								} else {
									this.exchange();
								}
							}
						});
					} else {
						this.valida();
					}
				} catch (e) {
					this.valida();
				}
			},
			async genJDurl() {
				try {
					let customerId = uni.getStorageSync('mobile');
					let param = {
						skuid: skuId,
						pid: customerId,
						couponurl: couponurl
					};
					let res = await this.$request.post('/coupon-product/jd/goods/unionUrl', {
						data: param
					});
					h5Url = res.data.data;
					console.log('JD h5url====' + h5Url);
					const urlbefore =
						'openapp.jdmobile://virtual?params=%7B%22category%22:%22jump%22,%22des%22:%22m%22,%22sourceValue%22:%22babel-act%22,%22sourceType%22:%22babel%22,%22url%22:%22';
					const urlafter = '%22,%22M_sourceFrom%22:%22H5_UL%22%7D';
					appUrl = urlbefore.concat(h5Url).concat(urlafter);
					this.exchangeCoupon();
				} catch (e) {
					console.log(e.message);
				}
			},
			jardePlatform() {
				callNative('onStartApp', {
					urlH5: h5Url,
					urlApp: appUrl
				}, '', () => {
					appNavigateTo(h5Url);
				});
			},
			async genPDDurl() {
				try {
					let customerId = uni.getStorageSync('mobile');
					console.log('pdd customerId===' + customerId);
					console.log('pdd token===' + uni.getStorageSync('token'));

					let res = await this.$request.post('/coupon-product/pdd/goods/unionUrl', {
						data: {
							skuid: skuId,
							custom_parameters: customerId
						}
					});
					//{skuid:'5957520990'}
					console.log('pdd datas ==' + res.data)
					console.log('pdd url ==' + res.data.data.url)
					h5Url = res.data.data.url;
					console.log('PDD h5url====' + h5Url);
					const pddheardUrl = 'pinduoduo://com.xunmeng.pinduoduo/duo_coupon_landing.html';
					appUrl = pddheardUrl.concat(h5Url.substr(h5Url.indexOf('?')));
					console.log('PDD appUrl====' + appUrl);
					this.exchangeCoupon();
				} catch (e) {
					console.log(e.message);
				}
			},
			valida() {
				onStartLogin()
			},

		}
	};
</script>

<style lang="scss"></style>
